﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
using System.IO;
using CTEM.Controllers.Global;

using CTEM.Models;
using System.Diagnostics;
using CTEM.Controllers.Global;

namespace CTEM.Controllers.DAO
{
    class WH_WarehouseDAO
    {
        /// <summary>
        /// 
        /// </summary>
        public WH_WarehouseDAO()
        {
            Transaction = null;
        }

        /// <summary>
        /// 
        /// </summary>
        private StackFrame _currentStackFrame;

        /// <summary>
        /// 
        /// </summary>
        public SqlTransaction Transaction { get; set; }

        /// <summary>
        /// 
        /// </summary>
        private SqlConnection _con;

        /// <summary>
        /// 
        /// </summary>
        SqlConnection Connection
        {
            get
            {
                if (_con == null)
                    _con = new SqlConnection(DatabaseInfo.ConnectionString);
                if (_con.State == ConnectionState.Closed)
                {
                    _con.Open();
                }
                return _con;
            }
            set
            {
                _con = value;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="warehouse"></param>
        /// <returns></returns>
        public long CreateWarehouse(WH_WarehouseDTO warehouse)
        {
            _currentStackFrame = new StackFrame();
            using (var cmd = new SqlCommand("[dbo].[WH_CreateWarehouse]", Connection) { CommandType = CommandType.StoredProcedure })
            {
                if (Transaction != null)
                {
                    cmd.Transaction = Transaction;
                }
                try
                {
                    string[] parameternames = { "@WarehouseName", 
                                                  "@ConstructionID", 
                                                  "@ManagerName", 
                                                  "@Description", 
                                                  "@Address", 
                                                  "@IsActive", 
                                                  "@IsDelete",
                                                  "@CreatedBy", 
                                                  "@CreatedDate", };
                    object[] parametervalues = { warehouse.WarehouseName, 
                                                   warehouse.ConstructionID, 
                                                   warehouse.ManagerName, 
                                                   warehouse.Description, 
                                                   warehouse.Address, 
                                                   warehouse.IsActive, 
                                                   warehouse.IsDelete,
                                                   warehouse.CreatedBy, 
                                                   warehouse.CreatedDate };
                    cmd.Parameters.AddRange(Global.Global.SetSqlParameter(parameternames, parametervalues));
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                            return Convert.ToInt64(reader[0]);
                    }
                    return 0;
                }
                catch (SqlException sql)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, sql.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return 0;
                }
                catch (Exception e)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, e.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return 0;
                }
                finally
                {
                    if (Transaction == null)
                        Connection.Close();
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="warehouse"></param>
        /// <returns></returns>
        public bool UpdateWarehouse(WH_WarehouseDTO warehouse)
        {
            _currentStackFrame = new StackFrame();
            using (var cmd = new SqlCommand("[dbo].[WH_UpdateWarehouse]", Connection) { CommandType = CommandType.StoredProcedure })
            {
                if (Transaction != null)
                {
                    cmd.Transaction = Transaction;
                }
                try
                {
                    string[] parameternames = { "@WarehouseID", 
                                                  "@WarehouseName", 
                                                  "@ManagerName", 
                                                  "@Description", 
                                                  "@Address", 
                                                  "@IsActive", 
                                                  "@IsDelete",
                                                  "@UpdatedBy", 
                                                  "@LastUpdated", };
                    object[] parametervalues = { warehouse.WarehouseID, 
                                                   warehouse.WarehouseName, 
                                                   warehouse.ManagerName, 
                                                   warehouse.Description, 
                                                   warehouse.Address, 
                                                   warehouse.IsActive, 
                                                   warehouse.IsDelete, 
                                                   warehouse.UpdatedBy, 
                                                   warehouse.LastUpdated };
                    cmd.Parameters.AddRange(Global.Global.SetSqlParameter(parameternames, parametervalues));
                    cmd.ExecuteReader();
                    return true;
                }
                catch (SqlException sql)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, sql.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return false;
                }
                catch (Exception e)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, e.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return false;
                }
                finally
                {
                    if (Transaction == null)
                        Connection.Close();
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="warehouseID"></param>
        /// <returns></returns>
        public bool DeleteWarehouse(long warehouseID)
        {
            _currentStackFrame = new StackFrame();
            using (var cmd = new SqlCommand("[dbo].[WH_DeleteWarehouse]", Connection) { CommandType = CommandType.StoredProcedure })
            {
                if (Transaction != null)
                {
                    cmd.Transaction = Transaction;
                }
                try
                {
                    cmd.Parameters.Add(new SqlParameter("@WarehouseID", warehouseID));
                    cmd.ExecuteNonQuery();
                    return true;
                }
                catch (SqlException sql)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, sql.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return false;
                }
                catch (Exception e)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, e.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return false;
                }
                finally
                {
                    if (Transaction == null)
                        Connection.Close();
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="warehouseID"></param>
        /// <returns></returns>
        public WH_WarehouseDTO GetWarehouseByID(long warehouseID)
        {
            _currentStackFrame = new StackFrame();
            using (var cmd = new SqlCommand("[dbo].[WH_GetWarehouseByID]", Connection))
            {
                if (Transaction != null)
                {
                    cmd.Transaction = Transaction;
                }
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new SqlParameter("@WarehouseID", warehouseID));
                try
                {
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            WH_WarehouseDTO warehouseDTO = new WH_WarehouseDTO
                            {
                                WarehouseID = Convert.ToInt64(reader["WarehouseID"]),
                                WarehouseName = Convert.ToString(reader["WarehouseName"]),
                                ConstructionID = Convert.ToInt64(reader["ConstructionID"]),
                                ManagerName = Convert.ToString(reader["ManagerName"]),
                                Description = Convert.ToString(reader["Description"]),
                                Address = Convert.ToString(reader["Address"]),
                                IsActive = Convert.ToBoolean(reader["IsActive"]),
                                IsDelete = Convert.ToBoolean(reader["IsDelete"]),
                                CreatedBy = Convert.ToString(reader["CreatedBy"]),
                                CreatedDate = Convert.ToDateTime(reader["CreatedDate"]),
                                UpdatedBy = Convert.ToString(reader["UpdatedBy"]),
                                LastUpdated = Convert.ToDateTime(reader["LastUpdated"])
                            };
                            return warehouseDTO;
                        }
                    }
                    return null;
                }
                catch (SqlException sql)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, sql.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return null;
                }
                catch (Exception e)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, e.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return null;
                }
                finally
                {
                    if (Transaction == null)
                        Connection.Close();
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="isActive"></param>
        /// <returns></returns>
        public List<WH_WarehouseDTO> LoadAllWarehouses(bool isActive)
        {
            _currentStackFrame = new StackFrame();
            using (var cmd = new SqlCommand("[dbo].[WH_GetAllWarehouse]", Connection))
            {
                if (Transaction != null)
                {
                    cmd.Transaction = Transaction;
                }
                cmd.CommandType = CommandType.StoredProcedure;
                if (isActive)
                {
                    cmd.Parameters.Add(new SqlParameter("@IsActive", isActive));
                }
                else
                {
                    cmd.Parameters.Add(new SqlParameter("@IsActive", DBNull.Value));
                }
                try
                {
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        List<WH_WarehouseDTO> listwarehouses = new List<WH_WarehouseDTO>();
                        while (reader.Read())
                        {
                            WH_WarehouseDTO warehouseDTO = new WH_WarehouseDTO
                            {
                                WarehouseID = Convert.ToInt64(reader["WarehouseID"]),
                                WarehouseName = Convert.ToString(reader["WarehouseName"]),
                                ConstructionID = Convert.ToInt64(reader["ConstructionID"]),
                                ManagerName = Convert.ToString(reader["ManagerName"]),
                                Description = Convert.ToString(reader["Description"]),
                                Address = Convert.ToString(reader["Address"]),
                                IsActive = Convert.ToBoolean(reader["IsActive"]),
                                IsDelete = Convert.ToBoolean(reader["IsDelete"]),
                                CreatedBy = Convert.ToString(reader["CreatedBy"]),
                                CreatedDate = Convert.ToDateTime(reader["CreatedDate"]),
                                UpdatedBy = Convert.ToString(reader["UpdatedBy"]),
                                LastUpdated = Convert.ToDateTime(reader["LastUpdated"])
                            };
                            listwarehouses.Add(warehouseDTO);
                        }
                        return listwarehouses;
                    }
                }
                catch (SqlException sql)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, sql.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return null;
                }
                catch (Exception e)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, e.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return null;
                }
                finally
                {
                    if (Transaction == null)
                        Connection.Close();
                }
            }
        }
    }
}
